class BSTNode:
    def __init__(self, key, value, left=None, right=None):
        self.key, self.value, self.left, self.right = key, value, left, right


NODE_LIST = [
    {'key': 60, 'left': 12, 'right': 90, 'is_root': True},
    {'key': 12, 'left': 4, 'right': 41, 'is_root': False},
    {'key': 4, 'left': 1, 'right': None, 'is_root': False},
    {'key': 1, 'left': None, 'right': None, 'is_root': False},
    {'key': 41, 'left': 29, 'right': None, 'is_root': False},
    {'key': 29, 'left': 23, 'right': 37, 'is_root': False},
    {'key': 23, 'left': None, 'right': None, 'is_root': False},
    {'key': 37, 'left': None, 'right': None, 'is_root': False},
    {'key': 90, 'left': 71, 'right': 100, 'is_root': False},
    {'key': 71, 'left': None, 'right': 84, 'is_root': False},
    {'key': 100, 'left': None, 'right': None, 'is_root': False},
    {'key': 84, 'left': None, 'right': None, 'is_root': False},
]


class BST:
    def __init__(self, root=None):
        self.root = root

    @classmethod
    def build_from(cls, node_list):
        cls.size = 0
        nodes = {}
        root = None
        for nodedict in node_list:
            key = nodedict['key']
            nodes[key] = BSTNode(key=key, value=key)
        for nodedict in node_list:
            key = nodedict['key']
            nodes[key].left = nodes.get(nodedict['left'])
            nodes[key].right = nodes.get(nodedict['right'])
            if nodedict['is_root']:
                root = nodes[key]
            cls.size += 1
        return cls(root) # cls()方法返回self对象，所以调用初始化方法

    def _bst_search(self, subtree, key):
        if subtree is None:
            return None
        if subtree.key == key:
            return subtree
        if key > subtree.key:
            return self._bst_search(subtree.right, key)
        if key < subtree.key:
            return self._bst_search(subtree.left, key)

    def get(self, key, deault=None):
        node = self._bst_search(self.root, key)
        if node is None:
            return deault
        else:
            return node.value

    def _bst_min_node(self, subtree):
        if subtree.left is None:
            return subtree
        else:
            return self._bst_min_node(subtree.left)

    def bst_min(self):
        node = self._bst_min_node(self.root)
        return node.value if node else None

    def _bst_max_node(self, subtree):
        if subtree.right is None:
            return subtree
        else:
            return self._bst_max_node(subtree.right)

    def bst_max(self):
        node = self._bst_max_node(self.root)
        return node.value if node else None

    def _bst_insert(self, subtree, key, value):
        if subtree is None:  # 插入的节点一定是根节点，包括 root 为空的情况
            subtree = BSTNode(key, value)
        if key > subtree.key:
            subtree.right = self._bst_insert(subtree.right, key, value)
        elif key < subtree.key:
            subtree.left = self._bst_insert(subtree.left, key, value)
        return subtree

    def add(self, key, value):
        # 先查找时候存在该key
        node = self._bst_search(self.root, key)
        if node is not None:  # 查找到该key，更新value
            node.value = value
            return False
        else:
            self.size += 1
            self._bst_insert(self.root, key, value)
            return True

    def _bst_remove(self, subtree, key):
        """
        3种情况
        1、删除节点为叶节点，直接删除就行
        2、删除中间节点，中间节点只有1个孩子节点的时候，该节点的关系直接由孩子节点和父节点联系
        3、删除中间节点，中间节点有2个孩子节点的时候，该节点删除关系由比该节点大的节点中最小的节点继承，即是该二叉查找树中序排序后的下个节点继承

        :param subtree: 树
        :param key: 需要查找节点的key
        :return: 返回subtree数
        """
        if subtree is None:  # 未找到该节点返回None
            return None
        if key < subtree.key:
            subtree.left = self._bst_remove(subtree.left, key)  # 删除后，subtree的左节点的树结构
        elif key > subtree.key:
            subtree.right = self._bst_remove(subtree.right, key)
        elif key == subtree.key:
            if subtree.left is None and subtree.right is None:  # 叶节点，返回 None 把其父亲指向它的指针置为 None
                subtree = None
            elif subtree.left is None or subtree.right is None: # 只有一个孩子节点
                if subtree.left is not None:
                    subtree = subtree.left
                else:
                    subtree = subtree.right
            elif subtree.left is not None and subtree.right is not None: # 2个孩子节点
                nextnode = self._bst_min_node(subtree.right) # 用于替代的节点 ，该节点需要移除
                self._bst_remove(subtree.right,nextnode.key)
                subtree = nextnode
        return subtree

    def remove(self,key):
        self.size -= 1
        return self._bst_remove(self.root,key)


def test_bst_tree():
    bst = BST.build_from(NODE_LIST)
    for node_dict in NODE_LIST:
        key = node_dict['key']
        assert bst.get(key) == key
    assert bst.size == len(NODE_LIST)
    assert bst.get(-1) is None    # 单例的 None 我们用 is 来比较

    assert bst.bst_min() == 1

    bst.add(0, 0)
    assert bst.bst_min() == 0

    bst.remove(12)
    assert bst.get(12) is None

    bst.remove(1)
    assert bst.get(1) is None

    bst.remove(29)
    assert bst.get(29) is None